package servlet;

import Dao.JdbcTools;
import com.alibaba.fastjson.JSONObject;
import model.Stu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/ajaxupdate")
public class ajaxupdate extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求，告知用户服务器的编码
        //获取json格式的字符串
        String datajson = req.getParameter("datajson");
        System.out.println("字符串datajson = " + datajson);
        //json格式转换json对象
        JSONObject jsonObject = JSONObject.parseObject(datajson.toString());
        //获取对象中各个属性的值
        String id = jsonObject.getString("id");
        System.out.println("idfsasfadg = " + id);
        String name = jsonObject.getString("name");
        String sex = jsonObject.getString("sex");
        String age = jsonObject.getString("age");
        String tel = jsonObject.getString("tel");
        String scores = jsonObject.getString("scores");
        String school = jsonObject.getString("school");

        try {
            int i = JdbcTools.update1("update stu set name=?,sex=?,age=?,tel=?,scores=?,school=? where id=?",
                    name, sex, age, tel, scores, school, id);
            System.out.println("i = " + i);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //数据输出
        System.out.println("name = " + name);
        System.out.println("sex = " + sex);
        System.out.println("age = " + age);
        System.out.println("tel = " + tel);
        System.out.println("scores = " + scores);
        System.out.println("school = " + school);


        PrintWriter writer = resp.getWriter();
        writer.write("success");

    }
}
